package coupon;

import activity.Activity;
import com.pingplusplus.model.RedEnvelope;
import enums.CouponType;
import helper.PingppHelper;
import jodd.util.StringUtil;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import models.weixin.WeixinRedBao;
import order.Order;
import play.Logger;
import play.db.jpa.Model;
import play.jobs.Job;
import shopcart.ShopCart;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by buhaoba on 2016/10/19.
 */
@Entity
@Table(name = "discount_coupons")
public class DiscountCoupon extends BaseModel {


    /**
     * 商户信息
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;


    /**
     * 活动标题
     */
    @Column(name = "title")
    public String title;


    /**
     * 使用的优先级
     */
    @Column(name = "priority")
    public Integer priority;

    /**
     * 开始日期
     */
    @Column(name = "begin_at")
    public Date beginAt;

    /**
     * 开始时间
     */
    @Column(name = "begin_times")
    public String beginTimes;

    /**
     * 结束日期
     */
    @Column(name = "end_at")
    public Date endAt;


    /**
     * 结束时间
     */
    @Column(name = "end_times")
    public String endTimes;

    /**
     * 最小赠送金额
     */
    @Column(name = "min_amount")
    public Double minAmount;

    /**
     * 最大赠送金额
     */
    @Column(name = "max_amount")
    public Double maxAmount;

    /**
     * 平均赠送金额
     */
    @Column(name = "avg_amount")
    public Double avgAmount;

    /**
     * 分多少个跨度
     */
    @Column(name = "grade")
    public Integer grade = 1;

    /**
     * 实际赠送金额
     */
    @Column(name = "amount")
    public Double amount;


    /**
     * 可使用最小比例
     */
    @Column(name = "min_proportion")
    public Double minProportion = 0.00D;

    /**
     * 可使用最大比例
     */
    @Column(name = "max_proportion")
    public Double maxProportion = 1.00D;

    /**
     * 平均比例
     */
    @Column(name = "avg_proportion")
    public Double avgProportion = 1.00D;

    /**
     * 类型
     */
    @Column(name = "type")
    @Enumerated(EnumType.STRING)
    public CouponType type;


    /**
     * 是否可累加
     */
    @Column(name = "is_accumulation")
    public Boolean isAccumulation;


    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 根据id查询
     * @param id
     * @return
     */
    public static DiscountCoupon findByDiscountCouponId(long id){
        return DiscountCoupon.find(" id = ? and deleted = ?",id ,DeletedStatus.UN_DELETED).first();
    }

    /**
     * 查询未删除订单
     * @return
     */
    public static List<DiscountCoupon> findByUnDeleted() {
        return DiscountCoupon.find("deleted = ?", DeletedStatus.UN_DELETED).fetch();
    }

    public static List<DiscountCoupon> findByAvailableByMerchant(Merchant merchant) {
        return DiscountCoupon.find("deleted = ? and beginAt < ? and endAt > ? and merchant = ?", DeletedStatus.UN_DELETED , new Date() , new Date() , merchant).fetch();
    }

    public static List<DiscountCoupon> findByAvailableByMerchantAndType(Merchant merchant , CouponType type) {
        return DiscountCoupon.find("deleted = ? and beginAt < ? and endAt > ? and merchant = ? and type = ?", DeletedStatus.UN_DELETED , new Date() , new Date() , merchant , type).fetch();
    }

    /**
     * 检测代金券
     * @param order
     */
    public static void checkToCoupon(Order order) {
        checkToCoupon(order.webUser , order.merchant);
    }


    /**
     * 赠送特定代金券
     * @param webUser
     * @param discountCoupon
     */
    public static void giveByCoupon(WebUser webUser, DiscountCoupon discountCoupon) {
        if(webUser == null || discountCoupon == null) {
            Logger.info("discountCoupon 或者 WebUser 不存在。 不能充值卡券");
            return;
        }

        WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(webUser);
        if(webUserCoupon == null) {
            webUserCoupon =  new WebUserCoupon(webUser , discountCoupon , discountCoupon.amount).save();
            new WebUserCouponHistory(webUserCoupon , "用户没有代金券 自动初始化充值" , discountCoupon.amount).save();
        } else {
//            if(discountCoupon.type.toString().indexOf("NO_BODY") < 1) {
//                webUserCoupon.amount += discountCoupon.amount;
//                webUserCoupon.modifyAt = new Date();
//                webUserCoupon.save();
//                new WebUserCouponHistory(webUserCoupon, discountCoupon.title, discountCoupon.amount).save();
//            }
        }
    }

    /**
     * 用户批量领取代金券
     * @param webUser
     * @param merchant
     * @param type
     * @param content
     */
    public static void giveCouponByType(WebUser webUser , Merchant merchant , CouponType type , String content) {
        List<DiscountCoupon> discountCouponList = DiscountCoupon.findByAvailableByMerchantAndType(merchant , type);
        WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(webUser);
        for(DiscountCoupon discountCoupon : discountCouponList) {
            if(type.toString().indexOf("NO_BODY") > 0) {
                if(webUserCoupon == null) {
                    webUserCoupon =  new WebUserCoupon(webUser , discountCoupon , discountCoupon.amount).save();
                    new WebUserCouponHistory(webUserCoupon , "用户没有代金券 自动初始化充值" , discountCoupon.amount).save();
                }
            } else {
                if(webUserCoupon == null) {
                    webUserCoupon =  new WebUserCoupon(webUser , discountCoupon , discountCoupon.amount).save();
                    new WebUserCouponHistory(webUserCoupon , "用户没有代金券 自动初始化充值" , discountCoupon.amount).save();
                } else {
                    webUserCoupon.amount += discountCoupon.amount;
                    webUserCoupon.modifyAt = new Date();
                    webUserCoupon.save();
                    new WebUserCouponHistory(webUserCoupon, content, discountCoupon.amount).save();
                }
            }


        }
    }

    /**
     * 异步操作
     * 检查 赠送代金券功能
     * @param webUser
     * @param merchant
     */
    public static void checkToCoupon(final WebUser webUser , final Merchant merchant) {
        new Job() {
            @Override
            public void doJob() throws Exception {
                WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(webUser);
                Long orderCount = Order.countByWebUser(webUser);
                List<DiscountCoupon> discountCouponList = DiscountCoupon.findByAvailableByMerchant(merchant);
                for(DiscountCoupon discountCoupon : discountCouponList) {
                    // 如果用户没有 赠送
                    if(discountCoupon.type == CouponType.NO_BODY && webUserCoupon == null) {
                        webUserCoupon =  new WebUserCoupon(webUser , discountCoupon , discountCoupon.amount).save();
                        new WebUserCouponHistory(webUserCoupon , "用户没有代金券 自动初始化充值" , discountCoupon.amount).save();
                    }

                    //首次下单赠送
                    if(discountCoupon.type == CouponType.FIRST_ORDER && orderCount < 1) {
                        if(webUserCoupon == null) {
                            webUserCoupon = new WebUserCoupon(webUser, discountCoupon, discountCoupon.amount).save();
                            new WebUserCouponHistory(webUserCoupon, "用户没有代金券 自动初始化充值", discountCoupon.amount).save();
                        } else {
                            webUserCoupon.amount += discountCoupon.amount;
                            webUserCoupon.modifyAt = new Date();
                            webUserCoupon.save();
                            new WebUserCouponHistory(webUserCoupon, "首次下单赠送", discountCoupon.amount).save();
                        }
                    }
                }
            }
        }.now();
    }



    public static Double disCountpayAmount(Double amount , WebUser webUser) {
        WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(webUser);
        Logger.info("用户 : %s 代金券 : %s" , webUser.nickName , webUserCoupon);
        if(webUserCoupon != null && webUserCoupon.amount != null && webUserCoupon.amount > 0) {
            Double disCountPay = (amount * webUserCoupon.discountCoupon.avgProportion) / 100;
            if(webUserCoupon.amount > disCountPay) {
                return disCountPay;
            } else {
                return webUserCoupon.amount;
            }
        }
        return 0d;
    }

    public static Double disCountpayAmount(Double amount , WebUser webUser , Merchant merchant) {
        if(merchant.playCoupon != null && merchant.playCoupon) {
            WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(webUser);
            Logger.info("用户 : %s 代金券 : %s", webUser.nickName, webUserCoupon);
            if (webUserCoupon != null && webUserCoupon.amount != null && webUserCoupon.amount > 0) {
                Double disCountPay = (amount * webUserCoupon.discountCoupon.avgProportion) / 100;
                if (webUserCoupon.amount > disCountPay) {
                    return disCountPay;
                } else {
                    return webUserCoupon.amount;
                }
            }
        }
        return 0d;

    }

}
